import React from 'react'
import PureRenderMixin from 'react-addons-pure-render-mixin'

import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import * as userInfoActionsFromOtherFile from '../../actions/userinfo'

import { hashHistory } from 'react-router'
import Header from '../../components/Header'
import LoginCom from '../../components/Login'

class Login extends React.Component {
    constructor(props, context) {
        super(props, context);
        this.shouldComponentUpdate = PureRenderMixin.shouldComponentUpdate.bind(this);
        this.state={
            checking:true
        }
    }
    render() {
        return (
            <div>
                <Header title="登录"/>
                {
                    this.state.checking
                    ? <div>loading...{/*等待中*/}</div>
                    : <LoginCom loginHandle={this.loginHandle.bind(this)}/>
                }
            </div>
        )
    }
    componentDidMount(){
        this.doCheck()
    }
    loginHandle(username){
        //登录成功之后的业务处理
        console.log('登录成功');
        //保存用户名
        const actions=this.props.userInfoActions;
        let userinfo=this.props.userinfo;
        userinfo.username=username;
        actions.update(userinfo);//保存在redux

        //跳转链接
        const params=this.props.params;
        const router=params.router;
        if(router){
            //跳转到指定的页面
            hashHistory.push(router)
        }else{
            //跳转默认页面 即用户中心页
            this.goUserPage();
        }
    }
    doCheck(){
        const userinfo=this.props.userinfo;
        if(userinfo.username){
            //已经登录
            this.goUserPage()
        }else{
            //尚未登录
            this.setState({
                checking:false
            })
        }
    }
    goUserPage(){
        hashHistory.push('/User')
    }
}

// 使用 require.ensure 异步加载，还不支持 ES6 的 export
//export default Login
// -------------------redux react 绑定--------------------
function mapStateToProps(state) {
    return {
        userinfo: state.userinfo
    }
}

function mapDispatchToProps(dispatch) {
    return {
        userInfoActions: bindActionCreators(userInfoActionsFromOtherFile, dispatch)
    }
}
export default connect(
    mapStateToProps,
    mapDispatchToProps
)(Login)